package com.tingyuge.thinking.spring.dependency.lookup;

import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/6/27
 */
public class ObjectProviderDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册 configuration class（配置类）
        applicationContext.register(ObjectProviderDemo.class);
        //启动应用上下文
        applicationContext.refresh();
        lookupByObjectProvider(applicationContext);

        lookupIfAvailable(applicationContext);
        lookupByStream(applicationContext);
    }

    private static void lookupByStream(AnnotationConfigApplicationContext applicationContext) {
        System.out.println();
        ObjectProvider<String> beanProvider = applicationContext.getBeanProvider(String.class);
        Iterable<String> strings= beanProvider;
        for (String string : strings) {
            System.out.println(string);
        }

    }

    private static void lookupIfAvailable(AnnotationConfigApplicationContext applicationContext) {
        ObjectProvider<User> beanProvider = applicationContext.getBeanProvider(User.class);
        User user = beanProvider.getIfAvailable(User::createUser);
        System.out.println("当前user 对象:"+ user);

    }

    @Bean
    @Primary
    public String helloWorld(){
        return "hello world";
    }

    @Bean
    public String message(){
        return "message";
    }


    private static void lookupByObjectProvider(AnnotationConfigApplicationContext annotationConfigApplicationContext){

        ObjectProvider<String> beanProvider = annotationConfigApplicationContext.getBeanProvider(String.class);
        System.out.println(beanProvider.getObject());

    }
}
